<template>
    <div>
        <div style="display: flex;">
            <van-icon name="arrow-left" @click="router.push('/taber/map')" style="font-size: 20px; margin-top:15px" />
            <input type="text" v-model="searchtqm" id="input_id" placeholder="请输入通勤地"
                style="width: 315px; border-radius: 5px; border: none;height: 36px; position: absolute; top: 6px; left:22px; background: rgb(242,242,242);" />
            <button @click="handleSearch"
                style="border: none; width: 70px; height: 36px; border-radius: 4px; background: rgb(245,124,0); color: white; position: absolute; top: 7px; z-index: 999; right: 10px;">
                搜索
            </button>
        </div>

        <!-- 历史搜索 -->
        <div v-if="historyData.length > 0">
            <div class="history">
                <h3>历史搜索</h3>
                <p @click="delstory"><img src="/public/imgage_gy/垃圾桶.png"
                        style="width: 26px; height: 26px;margin-top:5px" alt=""></p>
            </div>
            <ul class="hisdata">
                <li v-for="item, index in historyData" :key="index">
                    <span>{{ item }}</span>
                    <button @click="setComment(item)">设置为通勤地</button>
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter()

const searchtqm = ref('')
const historyData = ref([])

const handleSearch = () => {
    if (searchtqm.value.trim()) {
        // 存储历史搜索
        addHistory(searchtqm.value)
        // 使用路径来跳转到map页面，并传参
        router.push({
            path: '/map',
            query: { tqm: searchtqm.value }, //通过query传参
        })
    } else {
        alert('请输入有效的通勤地')
    }
}

// 添加历史记录
const addHistory = (query) => {
    let storeHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];
    // 如果历史记录存在，就移除重复的
    if (!storeHistory.includes(query)) {
        storeHistory.push(query)
        if (storeHistory.length > 5) {  //限制最多保存几条历史记录
            storeHistory.shift()
        }
        localStorage.setItem('searchHistory', JSON.stringify(storeHistory))
    }
    historyData.value = storeHistory
}

// 然后从localstorage中加载出历史记录
const loadHistory = () => {
    const storedHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];
    historyData.value = storedHistory
}
// 删除历史记录
const delstory = () => {
    localStorage.removeItem('searchHistory')
    historyData.value = []
}
// 设置通勤地
const setComment = (item) => {
    router.push({ path: '/map', query: { tqm: item } })
    searchtqm.value = item
}


onMounted(() => {
    loadHistory()
})


</script>

<style scoped>
.history {
    display: flex;
    justify-content: space-between;
    padding: 10px;
}

.hisdata {
    padding: 10px;
}

.hisdata li {
    display: flex;
    justify-content: space-between;
    margin: 5px 0;
}
</style>